const Question = require('../models/Question');
const { getTimestamp, getTwoDigits, reverseFormatObject, formatObject } = require('../utils/common');
const { sendResponse, sendListResponse } = require('../utils/response');
const { Op } = require('sequelize');
const QuestionCollection = require('../models/QuestionCollection');
const User = require('../models/User');
const QuestionCategory = require('../models/QuestionCategory');
const QuestionComment = require('../models/QuestionComment');
const sequelize = require('sequelize');

// 新增题目
exports.addQuestion = async (req, res) => {
  const { content, options, correctKey, difficulty, categoryId, userId } = req.body;
  try {
    if (!content || !options || !correctKey || !difficulty || !userId) {
      sendResponse(res, 400, "参数不完整");
      return;
    }
    const id = "182" + getTimestamp() + getTwoDigits();
    await Question.create({
      id,
      content,
      options,
      correct_key: correctKey,
      difficulty,
      category_id: categoryId,
      user_id: userId,
      is_delete: 0,
      status: 0
    });
    sendResponse(res, 200, "新增成功");
  } catch (error) {
    console.error('新增失败', error);
    sendResponse(res, 500, "新增失败");
  }
}

// 删除
exports.deleteQuestion = async (req, res) => {
  const { id } = req.body;
  try {
    const question = await Question.findByPk(id);
    if (!question) {
      sendResponse(res, 404, "题目不存在");
      return;
    }
    await question.update({
      is_delete: 1, // 逻辑删除
    });
    sendResponse(res, 200, "删除成功");
  } catch (error) {
    console.error('删除失败', error);
    sendResponse(res, 500, "删除失败");
  }
}

// 修改
exports.updateQuestion = async (req, res) => {
  const { id, content, options, correctKey, difficulty, categoryId, status } = req.body;
  try {
    const question = await Question.findByPk(id);
    if (!question) {
      sendResponse(res, 404, "题目不存在");
      return;
    }
    await question.update(reverseFormatObject({
      content,
      options,
      correct_key: correctKey,
      difficulty,
      category_id: categoryId,
      status,
    }));
    sendResponse(res, 200, "修改成功");
  } catch (error) {
    console.error('修改失败', error);
    sendResponse(res, 500, "修改失败");
  }
}


// 根据id查询详情
exports.getQuestionById = async (req, res) => {
  const id = req.params.id;
  try {
    // 查询题目详情，包括创建者和分类信息
    const question = await Question.findByPk(id, {
      include: [
        {
          model: User,
          as: 'creator',
          attributes: ['user_id', 'nickname']
        },
        {
          model: QuestionCategory,
          as: 'category',
          attributes: ['id', 'name']
        }
      ]
    });
    
    if (!question) {
      sendResponse(res, 404, "题目不存在");
      return;
    }
    
    // 获取评论数量
    const commentCount = await QuestionComment.count({
      where: {
        question_id: id,
      }
    });
    
    // 格式化题目数据
    const formattedQuestion = formatObject(question.toJSON());
    
    // 添加评论数量
    formattedQuestion.commentCount = commentCount;
    
    // 确保评分信息正确格式化
    formattedQuestion.userRatedDifficulty = parseFloat(formattedQuestion.userRatedDifficulty) || 0;
    formattedQuestion.userRatedQuality = parseFloat(formattedQuestion.userRatedQuality) || 0;
    
    sendResponse(res, 200, "查询成功", formattedQuestion);
  } catch (error) {
    console.error('查询失败', error);
    sendResponse(res, 500, "查询失败");
  }
}

// 根据条件分页查询题目列表
exports.getQuestionList = async (req, res) => {
  const { page = 1, pageSize = 10, content, difficulty, status, categoryId } = req.query;
  const offset = (page - 1) * pageSize;
  const limit = parseInt(pageSize);
  const where = {
    is_delete: 0,
  };
  if (content) {
    where.content = {
      [Op.like]: `%${content}%`,
    };
  }
  if (status) {
    where.status = status;
  }
  if (difficulty) {
    where.difficulty = difficulty;
  }
  if (categoryId) {
    where.category_id = categoryId;
  }
  try {
    // 列表查询，把创建者信息和分类信息也查询出来
    const { count, rows } = await Question.findAndCountAll({
      where,
      attributes: ['id', 'content', 'options', 'correct_key', 'difficulty', 
        'category_id', 'status', 'user_id', 'create_time', 
        'user_rated_difficulty', 'user_rated_quality', 'rating_count'],
      include: [
        {
          model: require('../models/User'),
          as: 'creator',
          attributes: ['user_id', 'nickname']
        },
        {
          model: require('../models/QuestionCategory'),
          as: 'category',
          attributes: ['id', 'name'],
          required: false
        }
      ],
      offset,
      limit
    });
    
    // 格式化结果
    const formattedRows = rows.map(item => {
      const data = formatObject(item.toJSON());
      // 确保评分信息正确格式化
      data.userRatedDifficulty = parseFloat(data.userRatedDifficulty) || 0;
      data.userRatedQuality = parseFloat(data.userRatedQuality) || 0;
      return data;
    });
    
    sendListResponse(res, 200, '查询成功', formattedRows, count);
  } catch (error) {
    console.error('查询失败', error);
    sendResponse(res, 500, "查询失败");
  }
}

// 查询带收藏量的题目列表
exports.getQuestionListWithCollectionCount = async (req, res) => {
  const { page = 1, pageSize = 10, content, difficulty, status, sortByCollection, userId, categoryId } = req.query;
  const offset = (page - 1) * pageSize;
  const limit = parseInt(pageSize);
  const where = {
    is_delete: 0,
  };
  
  if (content) {
    where.content = {
      [Op.like]: `%${content}%`,
    };
  }
  if (status) {
    where.status = status;
  }
  if (difficulty) {
    where.difficulty = difficulty;
  }
  if (categoryId) {
    where.category_id = categoryId;
  }
  
  try {
    // 先获取符合条件的题目
    const { count, rows } = await Question.findAndCountAll({
      where,
      attributes: ['id', 'content', 'options', 'correct_key', 'difficulty', 
        'category_id', 'status', 'user_id', 'create_time',
        'user_rated_difficulty', 'user_rated_quality', 'rating_count'],
      include: [
        {
          model: require('../models/QuestionCategory'),
          as: 'category',
          attributes: ['id', 'name'],
          required: false
        },
        {
          model: require('../models/User'),
          as: 'creator',
          attributes: ['user_id', 'nickname'],
          required: false
        }
      ],
      offset,
      limit,
      order: [['create_time', 'DESC']]
    });
    
    // 获取这些题目的收藏数量
    const questionIds = rows.map(item => item.id);
    
    // 如果没有题目，直接返回空数组
    if (questionIds.length === 0) {
      return sendListResponse(res, 200, '查询成功', [], 0);
    }
    
    // 获取每个题目的收藏数量
    const collectionCounts = await QuestionCollection.findAll({
      attributes: [
        'question_id',
        [sequelize.fn('COUNT', sequelize.col('question_id')), 'collection_count']
      ],
      where: {
        question_id: {
          [Op.in]: questionIds
        }
      },
      group: ['question_id'],
      raw: true
    });
    
    // 将收藏数量映射为对象，方便查找
    const collectionMap = {};
    collectionCounts.forEach(item => {
      collectionMap[item.question_id] = parseInt(item.collection_count);
    });

    // 获取每个题目的评论数量
    const commentCounts = await QuestionComment.findAll({
      attributes: [
        'question_id',
        [sequelize.fn('COUNT', sequelize.col('id')), 'comment_count']
      ],
      where: {
        question_id: {
          [Op.in]: questionIds
        },
      },
      group: ['question_id'],
      raw: true
    });

    // 将评论数量映射为对象
    const commentMap = {};
    commentCounts.forEach(item => {
      commentMap[item.question_id] = parseInt(item.comment_count);
    });

    // 获取当前用户的收藏状态
    const userCollections = await QuestionCollection.findAll({
      attributes: ['question_id'],
      where: {
        question_id: {
          [Op.in]: questionIds
        },
        user_id: userId
      },
      raw: true
    });

    // 将用户收藏状态映射为对象
    const userCollectionMap = {};
    userCollections.forEach(item => {
      userCollectionMap[item.question_id] = 1; // 改为1表示已收藏
    });
    
    // 格式化结果并添加收藏数量
    const formattedRows = rows.map(item => {
      const data = formatObject(item.toJSON());
      
      // 确保评分信息正确格式化
      data.userRatedDifficulty = parseFloat(data.userRatedDifficulty) || 0;
      data.userRatedQuality = parseFloat(data.userRatedQuality) || 0;
      
      return {
        ...data,
        collectionCount: collectionMap[item.id] || 0,
        commentCount: commentMap[item.id] || 0,
        isCollected: userCollectionMap[item.id] || 0 // 改为数字：0未收藏，1已收藏
      };
    });
    
    // 如果需要按收藏量排序
    if (sortByCollection === 'true') {
      formattedRows.sort((a, b) => b.collectionCount - a.collectionCount);
    }
    
    sendListResponse(res, 200, '查询成功', formattedRows, count);
  } catch (error) {
    console.error('查询失败', error);
    sendResponse(res, 500, "查询失败", { error: error.message });
  }
};

module.exports;
